//
//  UITextView+Extension.swift
//  EmoticonKeyBoard
//
//  Created by Arvin on 15/11/22.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit

extension UITextView {
    
    // 返回表情字符串
    func fullText() -> String {
        var strM = String()
        let textAttri = attributedText
        // 枚举textView的属性文本的内容, dict中是表情和文字对象, range是表情和文字的范围
        textAttri.enumerateAttributesInRange(NSMakeRange(0, textAttri.length), options: []) { (dict, range, _) -> Void in
            
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                // 获取文本
                strM += attachment.chs!
            } else {
                // 截取字符串
                strM += (textAttri.string as NSString).substringWithRange(range)
                
            }
        }
        return strM
    }
    
    // 显示表情
    func setupText(emoticon: Emoticon) {
        if emoticon.isEmpty  {
            return
        }
        
        if emoticon.isDelete {
            deleteBackward()
            return
        }
        
        if emoticon.code != nil {
            insertText(emoticon.codeStr!)
            return
        }
                
        // 1 获取textView的属性文本
        let textAttrib = attributedText
        // 1.1 将不可变的转成可变的属性文本
        let textAttribM = NSMutableAttributedString(attributedString: textAttrib)
        
        // 3 获取图片属性文本
        let range = selectedRange
        let attrubedAttach = EmoticonAttachment().getAttubitedString(font, emoticon: emoticon, range: range)
        textAttribM.replaceCharactersInRange(range, withAttributedString: attrubedAttach)
        
        // 4 给textView的属性文本赋值
        attributedText = textAttribM
        
        // 解决bug1 光标位置
        selectedRange = NSMakeRange(range.location + 1, 0)
        
    }
    
    
}